#include "SelectSvr.hpp"

#define CHECK_RET(ret) \
  if(!ret){\
    return 0;\
  }

int main(int argc, char* argv[]){
  if(argc < 3){
    printf("[ip:] [port]\n");
    return 0;
  }
  std::string ip = argv[1];
  uint16_t port = atoi(argv[2]);
  
  TcpSocket svr_tcp ;
  CHECK_RET(svr_tcp.CreateSocket());
  CHECK_RET(svr_tcp.Bind(ip, port));
  CHECK_RET(svr_tcp.Listen());

  SelectSvr select_svr;
  select_svr.AddFd(svr_tcp.GetFd());

  while(1){
    timeval timeout;
    timeout.tv_sec = 3;
    timeout.tv_usec = 0;
    std::vector<TcpSocket> clis;
    if(!select_svr.SelectWait(clis, &timeout)){
      continue;
    }
    for(auto& e : clis){
      if(svr_tcp.GetFd() == e.GetFd()){
        TcpSocket cli;
        sockaddr_in cli_addr;
        svr_tcp.Accept(cli, cli_addr);
        printf("Have a new connect: [ip:%s] [port:%d]\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
        select_svr.AddFd(cli.GetFd());
      }
      else{
        std::string buf;
        int ret = e.Recv(buf);
        if(ret > 0){
          printf("TcpSocket:[%d]", e.GetFd());
          printf("Client say:\"%s\"\n", buf.data());
        }
        else if(ret <= 0){
          select_svr.RemoveFd(e.GetFd());
          e.Close();
        }
      }
    }
  }
  return 0;
}
